import { Menu, MenuItemType } from '@kedacom/react-next'
import { useEffect, useState, useContext } from 'react'
import { SidebarRouterProps } from '@/router/routerInterface'
import { useNavigate } from 'react-router-dom'
import useMenusHook from '@/router/sidebarMenu'
import { AppContext } from './context'

interface MenuViewProps {
	pathname: string
}
const MenuView = ({ pathname }: MenuViewProps) => {
	const { system: systemInfo } = useContext(AppContext)
	const navigate = useNavigate()
	/**菜单项中高亮激活的菜单 */
	let [currentActiveMenu, setCurrentActiveMenu] = useState<string>('')
	/**当前可展示的所有菜单项 */
	let { sidebarMenu } = useMenusHook()

	/**点击菜单切换时 */
	const menuOnClick = (item: MenuItemType, id: string) => {
		navigate(id)
	}
	useEffect(() => {
		if (systemInfo.configWizardState === 0 && pathname !== '/configuration') {
			//若没有走过配置向导需要强制走配置向导
			navigate(`/configuration?type=init`)
		}
		// else if (systemInfo.ltsAlertState === 0 && pathname !== '/certificate/gm') {
		// 	navigate(`/certificate/gm`)
		// }
		else if (systemInfo.configWizardState === 1 && pathname === '/configuration') {
			//已走过配置向导，就需要强制跳转到登录页面
			navigate(`/home`)
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [pathname, systemInfo.configWizardState, systemInfo.ltsAlertState])
	/**根据路由的改变，更新对应的菜单的激活状态 */
	useEffect(() => {
		let isHomePage = pathname === '/home'
		/**要高亮的菜单项 */
		let activeObj: SidebarRouterProps = {
			id: '',
			path: '',
			title: '',
		}
		sidebarMenu.find((firstMenu) => {
			if (firstMenu.path === pathname) {
				activeObj = firstMenu
			}
			if (firstMenu.children && firstMenu.children.length) {
				firstMenu.children.find((secondMenu) => {
					if (secondMenu.path === pathname) {
						activeObj = secondMenu
					}
					return secondMenu.path === pathname
				})
			}
			return firstMenu.path === pathname
		})
		//如果是切换到首页，则取消菜单的高亮
		if (isHomePage) {
			setCurrentActiveMenu('')
		} else {
			//如果从菜单配置项中找到了路由地址，就高亮激活该菜单
			//如果路由地址，不在菜单项中，就保持上次的高亮的菜单，如路由更新至某个菜单下的详情页面
			if (activeObj && activeObj.path) {
				setCurrentActiveMenu(activeObj.path)
			}
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [pathname, sidebarMenu])
	return (
		<Menu
			active={currentActiveMenu}
			width={142}
			minWidth={64}
			data={sidebarMenu}
			onClick={(e, { item, id }) => {
				menuOnClick(item, id)
			}}
		></Menu>
	)
}

export default MenuView
